

import UIKit
import SVGAPlayer
import NetworkExtension
class XWHomeViewController: UIViewController, SVGAPlayerDelegate {
//    var XWSvgaPlayer: SVGAPlayer!
    private var providerManager:NETunnelProviderManager!
    
    @IBOutlet weak var XWSetButton: UIButton!
    
    @IBOutlet weak var XWSVGBackView: UIView!
    
    @IBOutlet weak var XWLinkButton: UIButton!
    
    
    @IBOutlet weak var XWSpeedBackView: UIView!
    
    @IBOutlet weak var XWSpeedLabel: UILabel!
    
    @IBOutlet weak var XWTimerLabel: UILabel!
    
    
    @IBOutlet weak var XWCountryImageView: UIImageView!
    
    @IBOutlet weak var XWCountryLabel: UILabel!
    
    @IBOutlet weak var XWDownloadLabl: UILabel!
    
    @IBOutlet weak var XWUploadLabel: UILabel!
    
    
    @IBOutlet weak var XWSpeedButton: UIButton!
    
    
    @IBOutlet weak var XWFileCardButton: UIButton!
    
    private var isNewStart:Bool!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if XWDataStateTool.shareManger.getIsConnectVPN(){
            XW_successLink()
        }else{
            XW_faileLink()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let isFirst = UserDefaults.standard.bool(forKey: "isFirst")
        if !isFirst{
            UserDefaults.standard.setValue(true, forKey: "isFirst")
            let homeNotice = XWHomeNoticeView.init(frame: CGRect.zero)
            self.view.addSubview(homeNotice)
            homeNotice.snp.makeConstraints { make in
                make.top.equalTo(self.view)
                make.left.equalTo(self.view)
                make.bottom.equalTo(self.view)
                make.right.equalTo(self.view)
            }
        }
        vpnLoad()
    }
    lazy var XWSvgaPlayer:SVGAPlayer = {
        var svgPlayer = SVGAPlayer.init()
        XWSVGBackView.addSubview(svgPlayer)
        svgPlayer.snp.makeConstraints { make in
            make.top.equalTo(XWSVGBackView)
            make.left.equalTo(XWSVGBackView)
            make.right.equalTo(XWSVGBackView)
            make.bottom.equalTo(XWSVGBackView)
        }
        svgPlayer.loops = 0
        svgPlayer.delegate = self
        return svgPlayer
    }()
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    // 列表
    @IBAction func XWListButtonClick(_ sender: UIButton) {
        if XWDataStateTool.shareManger.getIsConnectVPN(){
            let vc = XWServerViewController()
            PresentViewController(vc)
        }else{
            XWLink()
        }
    }
    // 设置
    @IBAction func XWSetButtonClick(_ sender: UIButton) {
        let setView = XWSetView(frame: .zero)
        self.view.addSubview(setView)
        setView.snp.makeConstraints { make in
            make.top.equalTo(self.view)
            make.left.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.right.equalTo(self.view)
        }
    }
    // 连接
    @IBAction func XWLinkButtonClick(_ sender: UIButton) {
        XWLink()
    }
    // 测速
    @IBAction func XWSpeedButtonClick(_ sender: UIButton) {
        if XWDataStateTool.shareManger.getIsConnectVPN(){
            let vc = XWSpeedViewController()
            PresentViewController(vc)
        }else{
            XWLink()
        }
    }
    // 翻牌
    @IBAction func XWFlipCardButtonClick(_ sender: UIButton) {
        if XWDataStateTool.shareManger.getIsConnectVPN(){
           let vc = XWFlipViewController()
            PresentViewController(vc)
        }else{
            XWLink()
        }
    }
    private func XWLink(){
        XWLinkButton.isHidden = true
        XWSVGBackView.isHidden = false
        let parser = SVGAParser.init()
        parser.parse(withNamed: "link", in: nil) { [self] videoItem in
            XWSvgaPlayer.videoItem = videoItem
            XWSvgaPlayer.startAnimation()
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.loadData()
        }
    }
  
    
}
extension XWHomeViewController {
    private func loadData() {
        let parameters = ["data":["node_id":""]]
        XWHttpTool.init().getNodeInfo(parameters) {[self] model in
            XWDataStateTool.shareManger.setXWNodeInfoModel(model.account_info!)
            self.startConnect(model.account_info!)
        } failureHandler: {[self] failure in
            self.XWSVGBackView.isHidden = true
            self.XWLinkButton.isHidden = false
            XWSvgaPlayer.stopAnimation()
        }

    }
    private func startConnect(_ model:XWNodeInfoModel) {
        if (providerManager == nil){
            return
        }
        let dic = ["add":model.ip!,"v":"2","ps":"\u{7f8e}\u{56fd} CloudFlare\u{8282}\u{70b9}","port":model.port!,"id":model.user_id!,"aid":"0","net":model.network!,"type":"","host":"oiictw.yydsii.com","path":"/","tls":""]
        printLog(dic)
        let session:NETunnelProviderSession = providerManager.connection as! NETunnelProviderSession
        let base64String = base64DicToString(["add":model.ip!,"v":"2","ps":"\u{7f8e}\u{56fd} CloudFlare\u{8282}\u{70b9}","port":model.port!,"id":model.user_id!,"aid":"0","net":model.network!,"type":"","host":"oiictw.yydsii.com","path":"/","tls":""])
        let uri:String = "vmess://"+base64String
        let providerConfiguration:Dictionary = ["type":"0","uri":uri,"global":"1"] as [String : NSObject]
        let protocolConfiguration:NETunnelProviderProtocol = providerManager.protocolConfiguration as! NETunnelProviderProtocol
        var copy = protocolConfiguration.providerConfiguration
        copy!["configuration"] = providerConfiguration
        protocolConfiguration.providerConfiguration = copy
        providerManager.saveToPreferences { error in
            if (error != nil){
                printLog("saveToPreferencesWithCompletionHandler:\(String(describing: error))")
            }
        }
        let tempDic = ["uri":uri,"global":"1"] as! [String:NSObject]
        do{
            try session.startVPNTunnel(options:tempDic)
        }catch{
            printLog("\(NETunnelProviderError.Code.self)")
        }
    }
}
extension XWHomeViewController {
    private func vpnLoad() {
        YDVPNManager.shared().fetch {[self] manager in
            self.providerManager = manager
            if (manager != nil) {
                NotificationCenter.default.addObserver(self, selector: #selector(homeConnectionStatusChanged), name: .NEVPNStatusDidChange, object: manager!.connection)
            }
            isNewStart = UserDefaults.standard.bool(forKey: "isNewStart")
            manager!.connection.stopVPNTunnel()
        }
        
    }
    @objc func homeConnectionStatusChanged(_ sender:Notification) {
        let connection:NEVPNConnection = sender.object as! NEVPNConnection
        switch connection.status {
            case .invalid:
            printLog("invalid")
            break
            case .disconnected:
            printLog("disconnected")
            if currentViewController() is XWHomeViewController{
                if !isNewStart{
                    UserDefaults.standard.removeObject(forKey: "isNewStart")
                    isNewStart = true
                }else{
                    self.XWSVGBackView.isHidden = true
                    self.XWLinkButton.isHidden = false
                    XWSvgaPlayer.stopAnimation()
                }
                
            }
            break
            case .connecting:
            printLog("home----->connecting")
            break
            case .connected:
            printLog("home----->connected")
            if currentViewController() is XWHomeViewController{
                XWDataStateTool.shareManger.setIsConnectVPN(true)
                XWDataStateTool.shareManger.resetTime()
                XW_successLink()
            }
            break
            case .reasserting:
            printLog("reasserting")
            break
            case .disconnecting:
            printLog("disconnecting")
            if currentViewController() is XWHomeViewController{
                
            }
            break
            @unknown default:
            break
        }
    }
    private func XW_successLink() {
        self.XWSVGBackView.isHidden = true
        self.XWLinkButton.isHidden = false
        self.XWLinkButton.isUserInteractionEnabled = false
        self.XWSetButton.isHidden = false
        self.XWLinkButton.setImage(UIImage.init(named: "home_linked"), for: .normal)
        XWSvgaPlayer.stopAnimation()
        XWSpeedBackView.isHidden = false
        XWDataStateTool.shareManger.timerLabel = XWTimerLabel
        XWDataStateTool.shareManger.XWSpeedLabel = XWSpeedLabel
        XWCountryImageView.sd_setImage(with: URL.init(string: XWDataStateTool.shareManger.getXWNodeInfoModel().flag ?? ""), placeholderImage:UIImage.init(named: "logo_default") )
        XWCountryLabel.text = XWDataStateTool.shareManger.getXWNodeInfoModel().country
        XWDataStateTool.shareManger.XWDownloadLabl = XWDownloadLabl
        XWDataStateTool.shareManger.XWUploadLabel = XWUploadLabel
        XWSpeedButton.setImage(UIImage(named: "home_speed"), for: .normal)
        XWFileCardButton.setImage(UIImage(named: "home_flip"), for: .normal)
    }
    private func XW_faileLink() {
        self.XWSVGBackView.isHidden = true
        self.XWLinkButton.isHidden = false
        XWSetButton.isHidden = true
        XWSvgaPlayer.stopAnimation()
        XWSpeedButton.setImage(UIImage(named: "home_map"), for: .normal)
        XWFileCardButton.setImage(UIImage(named: "home_scan"), for: .normal)
        XWSpeedBackView.isHidden = true
        self.XWLinkButton.setImage(UIImage.init(named: "home_disLink"), for: .normal)
    }
}
